import React, { useState, useEffect, useRef } from 'react';
import {
  Layout,
  Menu,
  Form,
  Input,
  Button,
  Typography,
  Row,
  Col,
  message,
  Breadcrumb,
  Modal,
  Select,
  Tabs
} from 'antd';
import AIChatModel from './AIChatModel';
const buttonContainerStyle: React.CSSProperties = {
  position: 'absolute',
  right: '0',
  top: '-36px',
  zIndex: '1',
  margin: '0'
};

const previewContainerStyle: React.CSSProperties = {
  marginTop: '8px',
  background: '#FFF',
  padding: '8px 16px',
  whiteSpace: 'pre-wrap'
};

const { TextArea } = Input;
const { Sider, Content } = Layout;


interface FrameworkContent {
  description?: string;
  expert_knowledge?: string;
  collect_info?: string;
  analysis_approach?: string;
  expression_requirements?: string;
  evaluation_criteria?: string;
}

interface Expert {
  id: string;
  description?: string;
  framework_content?: FrameworkContent;
}

interface Category {
  id: string;
  name: string;
  type?: string;
  subs?: Category[];
  key?: string;
  label?: string;
  children?: Category[];
}

interface CaseExample {
  id?: string;
  title?: string;
  [key: string]: any;
}

const AnalyzeBasePage = () => {
  const [form] = Form.useForm();
  const [formValues, setFormValues] = useState<FrameworkContent>({});
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [showPreview, setShowPreview] = useState<boolean>(false);
  const [showCaseModal, setShowCaseModal] = useState<boolean>(false);
  const [currentField, setCurrentField] = useState<string>('');
  const [caseExamples, setCaseExamples] = useState<CaseExample[]>([]);
  const caseCacheRef = useRef<Record<string, CaseExample>>({});
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const currentExpertId = useRef<string>('');
  const apiHead = '/kgflow/api/v1/'
  const framework = useRef<any>(null);
  useEffect(() => {
    fetchCategories();
  }, []);
  const transformCategories = (categories: Category[]): any[] => {
    return categories.map(item => {
      const menuItem: any = {
        key: item.id,
        label: item.name,
        ...item
      };
      if (item.subs && item.subs.length > 0) {
        menuItem.children = transformCategories(item.subs);
      } else {
        // 确保没有子项的item可以被点击
        menuItem.children = null;
      }
      return menuItem;
    });
  };
  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response: any = await fetch(apiHead + 'experts/framework-tree');
      console.log('获取分类数据:', response);
      if (!response.ok) {
        throw new Error('Failed to fetch categories');
      }
      const data = await response.json();
      console.log('分类数据:', data);
      setCategories(transformCategories(data.data.subs));
    } catch (err: any) {
      console.error('加载分类数据失败:', err.message);
      message.error('加载分类数据失败');
    } finally {
      setLoading(false);
    }
  };
  const onMenuSelect = async ({ key }: { key: string }) => {
    console.log('./////////////',key)
    try {
      setLoading(true);
      setSelectedCategory(key);

      // 获取专家数据
      const response = await fetch(`${apiHead}experts/types/${key}`);
      if (!response.ok) {
        throw new Error('获取专家数据失败');
      }
      const expertData = await response.json();
      if (expertData.data?.experts.length === 0) {
        message.warning('该分类暂未配置专家数据');
        form.resetFields();
        setSelectedCategory(key); // 更新selectedCategory为key而不是label
        setIsEditing(false);
        setShowPreview(false); // 无数据也切换到预览模式
        currentExpertId.current = '';
        return;
      }
      const expert: Expert = expertData.data?.experts[0];
      // 填充表单
      console.log(key)
      framework.current = {
        frameworkType: key, // 确保使用分类的key/id
        ...expert.framework_content,
        description: expert?.description
      }
      console.log('framework:', framework.current);
      form.setFieldsValue({
        frameworkType: key, // 确保使用分类的key/id
        ...expert.framework_content,
        description: expert?.description
      });


      currentExpertId.current = expert.id;
      setIsEditing(true);
      setShowPreview(true); // 成功获取数据后切换到预览模式
    } catch (error) {
      console.error('获取专家数据失败:', error);
      message.error('获取专家数据失败');
    } finally {
      setLoading(false);
    }
  };

  const findCategoryLabel = (key: string): string => {
    for (const category of categories) {
      if (category.key === key) return category.label || '';
      if (category.children) {
        for (const child of category.children) {
          if (child.key === key) return child.name || '';
        }
      }
    }
    return '';
  };

  const generateFrameworkOptions = (categories: Category[], level = 0): Array<{ label: string; value: string; disabled: boolean }> => {
    const options = categories.flatMap(category => {
      const prefix = '　'.repeat(level * 2); // 使用中文全角空格缩进
      const hasChildren = category.subs && category.subs.length > 0;
      const isSelectable = category.type === 'framework' && !hasChildren;

      const option = {
        label: `${prefix}${category.name}`,
        value: category.id,
        disabled: !isSelectable
      };

      if (hasChildren) {
        return [
          option,
          ...generateFrameworkOptions(category.subs || [], level + 1)
        ];
      }
      return option;
    });

    // 如果当前没有选中的分类，则使用第一个可选的选项
    if (!selectedCategory && options.length > 0) {
      const firstSelectableOption = options.find(option => !option.disabled);
      if (firstSelectableOption) {
        setSelectedCategory(firstSelectableOption.value);
        // 同时更新 framework.current
        framework.current = {
          frameworkType: firstSelectableOption.value,
          description: '',
          expert_knowledge: '',
          collect_info: '',
          analysis_approach: '',
          expression_requirements: '',
          evaluation_criteria: ''
        };
      }
    }

    return options;
  };

  const onFinish = async (values: {
    description: string;
    frameworkType: string;
    expert_knowledge?: string;
    collect_info?: string;
    analysis_approach?: string;
    expression_requirements?: string;
    evaluation_criteria?: string;
  }) => {
    try {
      const url = currentExpertId.current
        ? `${apiHead}experts/${currentExpertId.current}`
        : `${apiHead}experts`;

      const response = await fetch(url, {
        method: currentExpertId.current ? 'PUT' : 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          description: values.description,
          framework_content: (({ description, frameworkType, ...rest }) => rest)(values),
          framework_id: values.frameworkType
        })
      });
      if (!response.ok) {
        throw new Error('保存失败');
      }

      const data = await response.json();
      message.success('框架保存成功');
      console.log('API响应:', data);
    } catch (error) {
      console.error('保存失败:', error);
      message.error('框架保存失败');
    }
  };

  const handleCaseSelect = (example: { title: string; content: string }) => {
    form.setFieldsValue({ [currentField]: example.content });
    message.success(`已填充案例内容到${currentField}`);
    setShowCaseModal(false);
  };

  const openCaseModal = async (fieldName: string) => {
    const frameworkType = form.getFieldValue('frameworkType');
    if (!frameworkType) {
      message.error('请先选择框架类型');
      return;
    }
    setLoading(true);
    setCurrentField(fieldName);

    try {
      // 检查缓存中是否已有该框架类型的案例数据
      if (caseCacheRef.current[frameworkType]) {
        setCaseExamples(caseCacheRef.current[frameworkType][fieldName] || []);
        setShowCaseModal(true);
        return;
      }

      const response = await fetch(`${apiHead}experts/case/${frameworkType}`);
      if (!response.ok) {
        throw new Error('获取案例数据失败');
      }
      const data = await response.json();
      const examples = data.data.case;

      // 重组数据结构，将framework_content中的各项提取到顶层
      const transformedExamples = examples.framework_content
        ? {
          ...examples,
          ...examples.framework_content
        }
        : examples;
      delete transformedExamples.framework_content;
      // 更新缓存（保存完整transformedExamples）
      caseCacheRef.current = {
        ...caseCacheRef.current,
        [frameworkType]: transformedExamples
      };
      // 根据当前字段key获取对应案例数据
      setCaseExamples(transformedExamples[fieldName] || []);
      setShowCaseModal(true);
    } catch (error) {
      console.error('获取案例数据失败:', error);
      message.error('获取案例数据失败');
      setCaseExamples([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout style={{ height: 'calc(100vh - 80px)', overflow: 'hidden' }}>
      <Modal
        title="选择案例"
        open={showCaseModal}
        onCancel={() => setShowCaseModal(false)}
        footer={null}
        width={800}
      >
        <div style={{ height: '70vh', overflow: 'auto' }}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '24px' }}>
              <Typography.Text>加载案例中...</Typography.Text>
            </div>

          ) : caseExamples.length > 0 ? (
            Object.entries(caseExamples).map(([key, value]) => (
              key !== 'id' && key !== 'title' && (
                <div
                  key={key}
                  style={{
                    padding: '16px',
                    marginBottom: '16px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    cursor: 'pointer'
                  }}
                  onClick={() => handleCaseSelect({ title: key, content: String(value) })}
                >
                  <Typography.Title level={5}>示例：{parseInt(key) + 1}</Typography.Title>
                  <div style={{ marginLeft: '16px' }}>
                    {String(value).split('\n').map((item, i) => (
                      <p key={i}>{item}</p>
                    ))}
                  </div>
                </div>
              )
            ))
          ) : (
            <div style={{ textAlign: 'center', padding: '24px' }}>
              <Typography.Text>暂无案例数据</Typography.Text>
            </div>
          )}
        </div>
      </Modal>
      <Sider width={250} style={{ background: '#fff', height: 'calc(100vh - 80px)', overflowY: 'auto' }}>
        <Menu
          mode="inline"
          defaultOpenKeys={['1', '2']}
          style={{ overflowY: 'auto', height: 'calc(100vh - 80px)', padding: '10px 0 80px' }}
          items={categories as any}
          onSelect={onMenuSelect}
          expandIcon={() => <span className="ant-menu-submenu-arrow" />}
          selectable={true}
        />
      </Sider>
      <Content style={{ padding: '10px 20px 80px', overflowY: 'hidden', height: 'calc(100vh - 80px)',boxSizing: 'content-box'}}>
        <Tabs defaultActiveKey="1">
          <Tabs.TabPane tab="专家解读" key="1">
            <div style={{ padding: '0', background: '#f8fafc', borderRadius: '8px', height: 'calc(100vh - 140px)' }}>
              <AIChatModel title="专家解读" uploadable={false} configApi={{baseURL:"/langchain-backend", serviceRunPath:"/knowledge/master/analyze", framework:framework.current}} style={{height: 'calc(100vh - 140px)'}} propContent={`<div>当前框架：${findCategoryLabel(selectedCategory) || '<span style="color:red;">未选择</span>'}</div><div>对话框架：${findCategoryLabel(selectedCategory)}</div>`} />
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane tab="框架管理" key="2">
            <div style={{ padding: '16px', background: '#f8fafc', borderRadius: '8px',overflowY: 'auto', height: 'calc(100vh - 140px)' }}>
            {!showPreview ? (
              <React.Fragment>
                <Breadcrumb style={{ marginBottom: '16px' }}>
                  <Breadcrumb.Item>市场深度解读</Breadcrumb.Item>
                  <Breadcrumb.Item>框架生产</Breadcrumb.Item>
                </Breadcrumb>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                  <Typography.Title level={4} style={{ margin: 0 }}>框架生产</Typography.Title>
                  <Button
                    type="primary"
                    onClick={() => setShowPreview(true)}
                  >
                    预览
                  </Button>
                </div>
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={onFinish}
                  initialValues={{ frameworkType: selectedCategory }}
                >
                  <Form.Item
                    label="请选择框架类型"
                    name="frameworkType"
                    rules={[{ required: true, message: '请选择框架类型' }]}
                  >
                    <Select
                      options={generateFrameworkOptions(categories)}
                      placeholder="请选择框架类型"
                      showSearch
                      optionFilterProp="label"
                      style={{ width: '100%' }}
                    />
                  </Form.Item>

                  <Typography.Title level={5}>框架内容</Typography.Title>

                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        label="1. 框架功能介绍"
                        name="description"
                        rules={[{ required: true, message: '请输入框架功能介绍' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('description') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ description: e.target.value });
                              setFormValues({ ...formValues, description: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                  </Row>

                  <Typography.Title level={5}>2. 框架主体</Typography.Title>

                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        label="2.1 专家知识"
                        name="expert_knowledge"
                        rules={[{ required: true, message: '请输入专家知识' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <div style={buttonContainerStyle}>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => openCaseModal('expert_knowledge')}
                            >
                              show me your case
                            </Button>
                          </div>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('expert_knowledge') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ expert_knowledge: e.target.value });
                              setFormValues({ ...formValues, expert_knowledge: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item
                        label="2.2 收集信息"
                        name="collect_info"
                        rules={[{ required: true, message: '请输入收集信息' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <div style={buttonContainerStyle}>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => openCaseModal('collect_info')}
                            >
                              show me your case
                            </Button>
                          </div>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('collect_info') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ collect_info: e.target.value });
                              setFormValues({ ...formValues, collect_info: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item
                        label="2.3 解读思路"
                        name="analysis_approach"
                        rules={[{ required: true, message: '请输入解读思路' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <div style={buttonContainerStyle}>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => openCaseModal('analysis_approach')}
                            >
                              show me your case
                            </Button>
                          </div>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('analysis_approach') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ analysis_approach: e.target.value });
                              setFormValues({ ...formValues, analysis_approach: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item
                        label="2.4 表达要求"
                        name="expression_requirements"
                        rules={[{ required: true, message: '请输入表达要求' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <div style={buttonContainerStyle}>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => openCaseModal('expression_requirements')}
                            >
                              show me your case
                            </Button>
                          </div>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('expression_requirements') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ expression_requirements: e.target.value });
                              setFormValues({ ...formValues, expression_requirements: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item
                        label="2.5 评估标准"
                        name="evaluation_criteria"
                        rules={[{ required: true, message: '请输入评估标准' }]}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <div style={buttonContainerStyle}>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => openCaseModal('evaluation_criteria')}
                            >
                              show me your case
                            </Button>
                          </div>
                          <TextArea
                            rows={4}
                            value={form.getFieldValue('evaluation_criteria') || ''}
                            onChange={(e) => {
                              form.setFieldsValue({ evaluation_criteria: e.target.value });
                              setFormValues({ ...formValues, evaluation_criteria: e.target.value });
                            }}
                          />
                        </div>
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      {currentExpertId.current ? '更新' : '保存'}
                    </Button>
                    {isEditing && (
                      <Button
                        style={{ marginLeft: '16px' }}
                        onClick={() => {
                          form.resetFields();
                          setIsEditing(false);
                          currentExpertId.current = '';
                        }}
                      >
                        重置
                      </Button>
                    )}
                  </Form.Item>
                </Form>
              </React.Fragment>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
                  <Typography.Title level={4} style={{ margin: 0 }}>框架预览</Typography.Title>
                  <Button type="primary" onClick={() => setShowPreview(false)}>
                    返回编辑
                  </Button>
                </div>

                <div style={{
                  padding: '10px',
                  borderRadius: '4px',
                  flex: 1
                }}>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>框架类型：</strong>
                    <span>{findCategoryLabel(form.getFieldValue('frameworkType')) || form.getFieldValue('frameworkType') || '未选择'}</span>
                  </div>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>功能介绍：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('description') || '未填写'}
                    </div>
                  </div>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>专家知识：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('expert_knowledge') || '未填写'}
                    </div>
                  </div>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>收集信息：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('collect_info') || '未填写'}
                    </div>
                  </div>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>解读思路：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('analysis_approach') || '未填写'}
                    </div>
                  </div>
                  <div style={{ marginBottom: '12px' }}>
                    <strong>表达要求：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('expression_requirements') || '未填写'}
                    </div>
                  </div>
                  <div>
                    <strong>评估标准：</strong>
                    <div className='ant-input' style={previewContainerStyle}>
                      {form.getFieldValue('evaluation_criteria') || '未填写'}
                    </div>
                  </div>
                </div>
              </div>
            )}
            </div>
          </Tabs.TabPane>
        </Tabs>
      </Content>
    </Layout>
  );
};

export default AnalyzeBasePage;
